﻿using DevExpress.Utils.Win;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraGrid.Demos.util;
using DevExpress.XtraGrid.Editors;
using DevExpress.XtraLayout;
using DevExpress.XtraReports.UI;
using DXApplicationTangche.report;
using DXApplicationTangche.UC.下单MTO.Service;
using DXApplicationTangche.UC.金蝶.dto;
using DXApplicationTangche.UC.面料审核.Service;
using DXApplicationTangche.UC.面料库存.入库.service;
using DXApplicationTangche.UC.项目成果管理.service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DXApplicationTangche.UC.面料审核
{
    public partial class Form下达采购订单 : DevExpress.XtraEditors.XtraForm
    {
        private MaterialRequirementQueryDTO materialRequirementQueryDTO = new MaterialRequirementQueryDTO();
        private List<MaterialDetailDTO> materialDetailDTOs = new List<MaterialDetailDTO>();
        private List<MaterialPurchaseDetailDTO> materialPurchaseDetailDTOs = new List<MaterialPurchaseDetailDTO>();
        private List<StockOutDetailDTO> stockOutDetailDTOs = new List<StockOutDetailDTO>();
        public String fnumber { get; set; }
        public String fshortname { get; set; }
        public String supplierid { get; set; }
        public String supplierName { get; set; }

        public String materialRequirementId { get; set; }
        private KindDeeApplyReturnDTO kingDeeResultDTO保存出库单 = new KindDeeApplyReturnDTO();


        public Form下达采购订单(String id)
        {
            InitializeComponent();
            //供应商赋值
            this.searchLookUpEdit供应商.Properties.DataSource = 入库Service.getSupplierAll();
            //传参，获取物料需求计划id
            this.materialRequirementId = id;
            this.materialRequirementQueryDTO = 面料审核Service.getMaterialRequirementQueryById(id);
            this.gridControl待采购面料一览.DataSource = this.materialRequirementQueryDTO.materialRequirementDTOS;
            this.gridControl采购订单一览.DataSource = this.materialRequirementQueryDTO.materialPurchaseTitleDTOS;
            this.gridView采购订单一览.ExpandAllGroups();
            //根据类型判断 采购和出库按钮是否可用
            if (this.materialRequirementQueryDTO.complete)
            {
                this.simpleButton下达采购订单.Enabled = false;
                this.textBox面料审核出库扫码.Enabled = false;
                MessageBox.Show("已完成面料审核，请勿重复操作");
                return;
            }
        }

        private void gridView待采购面料一览_DoubleClick(object sender, EventArgs e)
        {
            //获取面料号和固定损耗总计
            String fname = this.gridView待采购面料一览.GetRowCellValue(this.gridView待采购面料一览.FocusedRowHandle, "fname").ToString();
            Double inventory = Convert.ToDouble(this.gridView待采购面料一览.GetRowCellValue(this.gridView待采购面料一览.FocusedRowHandle, "inventory"));
            //根据面料号查询金蝶fnumber
            MaterialDetailDTO materialDetailDTO面料信息 = 面料审核Service.getMaterialDetail(fname);
            this.materialDetailDTOs.Add(materialDetailDTO面料信息);
            this.materialPurchaseDetailDTOs.Clear();
            //添加到采购订单明细
            foreach (MaterialDetailDTO materialDetailDTO in this.materialDetailDTOs)
            {
                this.materialPurchaseDetailDTOs.Add(new MaterialPurchaseDetailDTO(materialDetailDTO面料信息.fname, materialDetailDTO面料信息.fnumber, materialDetailDTO面料信息.fmaterialid, inventory));
            }
            //一览显示
            this.gridControl面料采购列表.DataSource = this.materialPurchaseDetailDTOs;
            this.gridView面料采购列表.RefreshData();
        }
        #region
        private void searchLookUpEdit供应商_Popup(object sender, EventArgs e)
        {
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clear供应商Btn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        private void searchLookUpEdit供应商View_Click(object sender, EventArgs e)
        {
            int[] a = this.searchLookUpEdit供应商.Properties.View.GetSelectedRows();
            if (a.Length > 0)
            {
                foreach (int rowHandle in a)
                {
                    this.fnumber = this.searchLookUpEdit供应商.Properties.View.GetRowCellValue(rowHandle, "fnumber").ToString();
                    this.fshortname = this.searchLookUpEdit供应商.Properties.View.GetRowCellValue(rowHandle, "fshortname").ToString();
                    this.supplierid = this.searchLookUpEdit供应商.Properties.View.GetRowCellValue(rowHandle, "fsupplierid").ToString();
                    this.supplierName = this.searchLookUpEdit供应商.Properties.View.GetRowCellValue(rowHandle, "fname").ToString();
                }
            }
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clear供应商Btn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit供应商.ToolTip = null;
            searchLookUpEdit供应商.EditValue = null;
        }
        private void searchLookUpEdit供应商_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
            {
                e.DisplayText = this.fshortname;
            }
        }
        #endregion

        private void simpleButton下达采购订单_Click(object sender, EventArgs e)
        {
            //点击按钮时先查询，complete为true时不能调用任何方法
            this.materialRequirementQueryDTO = 面料审核Service.getMaterialRequirementQueryById(this.materialRequirementId);
            if (this.materialRequirementQueryDTO.complete)
            {
                this.simpleButton下达采购订单.Enabled = false;
                this.textBox面料审核出库扫码.Enabled = false;
                MessageBox.Show("已完成面料审核，请勿重复操作");
                return;
            }
            if (String.IsNullOrEmpty(this.fnumber))
            {
                MessageBox.Show("请选择供应商");
                return;
            }
            if(this.materialPurchaseDetailDTOs.Count == 0)
            {
                MessageBox.Show("请选择面料");
                return;
            }
            //保存采购订单、传供应商和采购明细
            //保存采购订单后返回采购订单fid、fnumber
            KindDeeApplyReturnDTO kingDeeResultDTO保存采购订单 = 面料审核Service.保存采购订单(this.fnumber, this.materialPurchaseDetailDTOs);
            //采购订单保存成功后调用
            if (kingDeeResultDTO保存采购订单.IsSuccess)
            {
                //保存采购订单后调用补充采购订单抬头
                面料审核Service.generateMaterialPurchase(
                    this.materialRequirementId,
                    kingDeeResultDTO保存采购订单.FId,
                    kingDeeResultDTO保存采购订单.FNumber,
                    this.supplierid,
                    this.supplierName,
                    this.materialPurchaseDetailDTOs);
                //调用完成后刷新显示采购订单
                this.刷新();
            }
            else
            {
                MessageBox.Show(kingDeeResultDTO保存采购订单.SuccessMessages);
                return;
            }
        }

        private void simpleButton面料审核出库_Click(object sender, EventArgs e)
        {
            //点击按钮时先查询，complete为true时不能调用任何方法
            //this.materialRequirementQueryDTO = 面料审核Service.getMaterialRequirementQueryById(this.materialRequirementId);
            //if (this.materialRequirementQueryDTO.complete)
            //{
            //    this.simpleButton面料审核出库.Enabled = false;
            //    this.simpleButton下达采购订单.Enabled = false;
            //    MessageBox.Show("已完成面料审核，请勿重复操作");
            //    return;
            //}
            foreach (MaterialRequirementDTO materialRequirementDTO in this.materialRequirementQueryDTO.materialRequirementDTOS)
            {
                MaterialDetailDTO materialDetailDTO面料信息 = 面料审核Service.getMaterialDetail(materialRequirementDTO.fname);
                this.stockOutDetailDTOs.Add(new StockOutDetailDTO(materialDetailDTO面料信息.fnumber, materialRequirementDTO.inventory));
            }
            //保存出库单
            this.kingDeeResultDTO保存出库单 = 面料审核Service.保存出库单(this.stockOutDetailDTOs);
            this.刷新();
            //保存出库单后调用
            //面料审核Service.generateMaterialStockOut(this.materialRequirementId, kingDeeResultDTO保存出库单.Fid, kingDeeResultDTO保存出库单.Fnumber);
        }
        private void 刷新()
        {
            this.materialRequirementQueryDTO = 面料审核Service.getMaterialRequirementQueryById(this.materialRequirementId);
            this.gridControl待采购面料一览.DataSource = this.materialRequirementQueryDTO.materialRequirementDTOS;
            this.gridControl采购订单一览.DataSource = this.materialRequirementQueryDTO.materialPurchaseTitleDTOS;
            if (this.materialRequirementQueryDTO.complete)
            {
                this.simpleButton下达采购订单.Enabled = false;
                this.textBox面料审核出库扫码.Enabled = false;
            }
        }

        private void simpleButtonPDF_Click(object sender, EventArgs e)
        {
            string saveDirectoryPath = @"pdf\";
            //根据对应的shopCD是否为空，对应不同的模板——有地址的和没有地址的
            //shopCD为空，无地址
            if (String.IsNullOrEmpty(this.materialRequirementQueryDTO.shopRightQueryFacadeDTO.shopCd))
            {
                XtraReport面料领用出库单 report = new XtraReport面料领用出库单(this.materialRequirementQueryDTO);
                ReportPrintTool tool = new ReportPrintTool(report);
                tool.ShowPreview();
                //  1.生成pdf文件保存到程序
                //report.ExportToPdf(saveDirectoryPath + this.kingDeeResultDTO保存出库单.FNumber + @".pdf");
            }
            //shopCD不为空，有地址
            else
            {
                XtraReport生产计划单带地址 report = new XtraReport生产计划单带地址(this.materialRequirementQueryDTO);
                ReportPrintTool tool = new ReportPrintTool(report);
                tool.ShowPreview();
                //  1.生成pdf文件保存到程序
                //report.ExportToPdf(saveDirectoryPath + this.kingDeeResultDTO保存出库单.FNumber + @".pdf");
            }

            //XtraReport面料领用出库单 report = new XtraReport面料领用出库单(this.materialRequirementQueryDTO);
            ////  循环取details并清洗尺寸
            ////report.DataSource = this.materialRequirementQueryDTO;
            //ReportPrintTool tool = new ReportPrintTool(report);
            //tool.ShowPreview();
            //string saveDirectoryPath = @"pdf\";
            ////  1.生成pdf文件保存到程序
            //report.ExportToPdf(saveDirectoryPath + this.kingDeeResultDTO保存出库单.FNumber + @".pdf");
            ////  2、上传pdf文件
            //面料审核Service.uploadFile(
            //                this.kingDeeResultDTO保存出库单.FNumber,
            //                saveDirectoryPath + this.kingDeeResultDTO保存出库单.FNumber + @".pdf"
            //            );
        }

        private void textBox面料审核出库_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyValue == 13)
            {
                if (String.IsNullOrEmpty(this.textBox面料审核出库扫码.Text))
                {
                    MessageBox.Show("无扫描信息");
                    return;
                }
                //判断扫描的工牌是否正确
                String mnemonic = 项目成果Service.get判断扫描员工码是否正确(this.textBox面料审核出库扫码.Text.Trim());
                if (String.IsNullOrWhiteSpace(mnemonic))
                {
                    this.textBox面料审核出库扫码.Clear();
                    MessageBox.Show("扫描员工码错误，请重新扫描");
                    return;
                }
                //获取出库单明细 面料号，数量
                foreach (MaterialRequirementDTO materialRequirementDTO in this.materialRequirementQueryDTO.materialRequirementDTOS)
                {
                    MaterialDetailDTO materialDetailDTO面料信息 = 面料审核Service.getMaterialDetail(materialRequirementDTO.fname);
                    this.stockOutDetailDTOs.Add(new StockOutDetailDTO(materialDetailDTO面料信息.fnumber, materialRequirementDTO.inventory));
                }
                ////保存出库单
                this.kingDeeResultDTO保存出库单 = 面料审核Service.保存出库单(this.stockOutDetailDTOs);
                //判断出库单是否保存成功
                //保存成功，调用pdf出库单
                if (kingDeeResultDTO保存出库单.IsSuccess)
                {
                    //pdf
                    string saveDirectoryPath = @"pdf\";
                    //根据对应的shopCD是否为空，对应不同的模板——有地址的和没有地址的
                    //shopCD为空，无地址
                    if (String.IsNullOrEmpty(this.materialRequirementQueryDTO.shopRightQueryFacadeDTO.shopCd))
                    {
                        XtraReport面料领用出库单 report = new XtraReport面料领用出库单(this.materialRequirementQueryDTO);
                        //  1.生成pdf文件保存到程序
                        report.ExportToPdf(saveDirectoryPath + this.kingDeeResultDTO保存出库单.FNumber + @".pdf");
                    }
                    //shopCD不为空，有地址
                    else
                    {
                        XtraReport生产计划单带地址 report = new XtraReport生产计划单带地址(this.materialRequirementQueryDTO);
                        //  1.生成pdf文件保存到程序
                        report.ExportToPdf(saveDirectoryPath + this.kingDeeResultDTO保存出库单.FNumber + @".pdf");
                    }
                    //  2、上传pdf文件
                    String re = 面料审核Service.generateMaterialStockOut(
                                    this.materialRequirementId,
                                    this.kingDeeResultDTO保存出库单.FId,
                                    this.kingDeeResultDTO保存出库单.FNumber,
                                    this.textBox面料审核出库扫码.Text.Trim(),
                                    saveDirectoryPath + this.kingDeeResultDTO保存出库单.FNumber + @".pdf"
                                );
                    PlainMessageResult plainMessageResult面料审核出库 = FunctionHelper.JsonDeserialization<PlainMessageResult>(re);
                    ;                //返回值200 保存成功
                    if ("200".Equals(plainMessageResult面料审核出库.errorCode))
                    {
                        MessageBox.Show("面料审核出库完成");
                    }
                    else
                    {
                        MessageBox.Show(plainMessageResult面料审核出库.errorMessage);
                    }
                    try { File.Delete(saveDirectoryPath + this.kingDeeResultDTO保存出库单.FNumber + @".pdf"); } catch { }
                    this.刷新();
                }
                //出库单保存失败，返回错误信息
                else
                {
                    MessageBox.Show(kingDeeResultDTO保存出库单.SuccessMessages);
                    return;
                }
            }
            //this.textBox面料审核出库扫码.Clear();
        }
    }
}
